package com.slipper.groovy.util;

import cn.hutool.extra.ftp.AbstractFtp;
import cn.hutool.extra.ftp.Ftp;
import cn.hutool.extra.ftp.FtpConfig;
import cn.hutool.extra.ftp.FtpMode;
import cn.hutool.extra.ssh.Sftp;
import com.slipper.exception.CommonException;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class FtpUtil implements AutoCloseable {
    private final List<AbstractFtp> ftpList = new ArrayList<>();

    public AbstractFtp getFtp(String type, String ip, int port, String username, String password) {
        FtpConfig config = new FtpConfig(ip, port, username, password, StandardCharsets.UTF_8);
        AbstractFtp ftp;
        if ("ftp".equalsIgnoreCase(type)) {
            ftp = new Ftp(config, FtpMode.Passive);
        } else {
            ftp = new Sftp(config);
        }
        ftpList.add(ftp);
        return ftp;
    }

    @Override
    public void close() throws Exception {
        ftpList.forEach(ftp -> {
            try {
                ftp.close();
            } catch (IOException e) {
                throw new CommonException("FTP关闭异常！", e);
            }
        });
    }
}
